package com.sdvdxl.util;

import java.io.IOException;
import java.util.Properties;

import javax.servlet.ServletContext;

public class GlobalVars {
	private static GlobalVars gvar;
	private Properties properties;
	private String blogPath;
	private ServletContext application;
	private int pageSize;
	private static LoggerUtil logger = new LoggerUtil(GlobalVars.class);

	private GlobalVars() {
	}

	public ServletContext getContext() {
		return application;
	}

	public void setContext(ServletContext context) {
		this.application = context;
	}

	public static GlobalVars getInstance() {
		if (gvar == null) {
			synchronized (GlobalVars.class) {
				if (gvar == null) {
					gvar = new GlobalVars();
				}
			}
		}

		return gvar;
	}

	public void init() {
		properties = new Properties();
		logger.info("初始化全局变量");
		try {
			properties.load(GlobalVars.class.getClassLoader()
					.getResourceAsStream("other.properties"));
		} catch (IOException e) {
			logger.error("初始化全局变量失败");
			logger.error(e);
		}
		
		getRealPath();
		getPageSizeFromConfig();
	}

	private void getRealPath() {
		if (null==blogPath) {
			blogPath = properties.getProperty("blogPath");
			if (null==blogPath) {
				logger.warn("未找到博文存放目录");
				blogPath = application.getRealPath("/");
				logger.warn("已将博文目录设置为："+blogPath);
			}
		}
	}
	
	private void getPageSizeFromConfig() {
		try {
			pageSize = Integer.parseInt(properties.getProperty("pageSize", "10"));
		} catch(NumberFormatException e) {
			logger.warn(e);
			logger.debug("已将pageSize设置为： 10");
			pageSize = 10;
		}
	}
	
	public String getBlogPath() {
		return blogPath;
	}

	/**
	 * 取得分页大小
	 * @return
	 */
	public int getPageSize() {
		return pageSize;
	}
}
